package cn.com.backstage.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import cn.com.api.entity.ApiT_enums;
import cn.com.api.entity.ApiU_coupon;
import cn.com.api.service.ApiT_enumsService;
import cn.com.api.service.ApiU_couponService;
import cn.com.backstage.controller.base.U_couponBaseController;
import cn.com.util.*;

/**
 * 优惠券控制器
 * 
 * @author Administrator
 *
 */
@Controller
@RequestMapping(Utils.SYS_BACKSTAGE + "/")
public class U_couponController extends U_couponBaseController {

	// 日志工具
	private static Logger logger = Logger.getLogger(U_couponController.class);

	@Autowired
	private ApiU_couponService apiU_couponService;

	@Autowired
	private ApiT_enumsService apiT_enumsService;

	/**
	 * 优惠券列表
	 * 
	 * @return
	 */
	@RequestMapping(value = "coupon-list")
	public ModelAndView u_coupon_list(HttpServletRequest request, HttpServletResponse response) throws Exception {

		ModelAndView mv = new ModelAndView("forward:/backstage/u_coupon_list.jsp");
		Map<String, Object> param = new HashMap<String, Object>();
		try {
			List<ApiT_enums> classify = apiT_enumsService.findT_enumssByItem_key("coupon_classify");
			List<ApiT_enums> classifys = apiT_enumsService.findT_enumssByParent_id(classify.get(0).getId() + "");
			mv.addObject("match_classifys_list", classifys);

			List<ApiT_enums> preferentia = apiT_enumsService.findT_enumssByItem_key("coupon_preferential");
			List<ApiT_enums> preferentias = apiT_enumsService.findT_enumssByParent_id(preferentia.get(0).getId() + "");
			mv.addObject("match_preferentias_list", preferentias);

			String coupon_cate_id = request.getParameter("coupon_cate_id");
			String coupon_type = request.getParameter("coupon_type");
			String flag_type = request.getParameter("flag_type");
			String id = request.getParameter("id");
			logger.info("======[U_couponController[u_coupon_list[参数coupon_id:" + coupon_cate_id + ",coupon_type:"
					+ coupon_type + ",flag_type:" + flag_type + "]]]=======");

			if (flag_type != null) {
				param.put("flag_type", flag_type);
			}
			if (coupon_cate_id != null && !"-1".equals(coupon_cate_id)) {
				param.put("coupon_cate_id", coupon_cate_id);
				mv.addObject("coupon_cate_id", coupon_cate_id);
			}
			if (coupon_type != null && !"-1".equals(coupon_type)) {
				param.put("coupon_type", coupon_type);
				mv.addObject("coupon_type", coupon_type);
			}
			if (id != null && "two".equals(id)) {
				param.put("flag_type", "1");
			}
			if (id != null && "three".equals(id)) {
				param.put("flag_type", "2");
			}

			param.put("curDate", new Date());
			List<ApiU_coupon> u_coupons = apiU_couponService.findU_couponsByCondition(param);
			mv.addObject("u_coupons", u_coupons);
			mv.addObject("id", id);
		} catch (Exception e) {
			logger.error("======[U_couponController[u_coupon_list[查询优惠券列表错误]]]=======", e);
		}

		return mv;
	}

	/**
	 * 优惠券添加
	 */
	@RequestMapping(value = "coupon-add")
	public void u_coupon_add(HttpServletRequest request, HttpServletResponse response) throws Exception {

		Map<String, Object> map = new HashMap<String, Object>();
		try {
			List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
			Map<String, Object> param = new HashMap<String, Object>();

			String coupon_id = request.getParameter("coupon_id");
			String coupon_cate_id = request.getParameter("coupon_cate_id");
			String corp_name = request.getParameter("corp_name");
			String corp_adress = request.getParameter("corp_adress");
			String range = request.getParameter("range");
			String corp_mobile = request.getParameter("corp_mobile");
			String business_hours = request.getParameter("business_hours");
			String coupon_type = request.getParameter("coupon_type");
			String description = request.getParameter("description");
			String[] coupon_amout = request.getParameterValues("coupon_amout");
			String[] use_limit1 = request.getParameterValues("use_limit1");
			String[] coupon_count = request.getParameterValues("coupon_count");
			String[] end_time = request.getParameterValues("end_time");
			String regioninfo = request.getParameter("regioninfo");
			String latitude = request.getParameter("latitude");
			String longitude = request.getParameter("longitude");
			logger.info("======[U_couponController[u_coupon_add[参数coupon_id:" + coupon_id + ",coupon_cate_id:"
					+ coupon_cate_id + ",corp_name:" + corp_name + ",corp_adress:" + corp_adress + "]]]=======");
			logger.info("======[U_couponController[u_coupon_add[参数range:" + range + ",corp_mobile:" + corp_mobile
					+ ",business_hours:" + business_hours + ",coupon_type:" + coupon_type + ",regioninfo:" + regioninfo
					+ "]]]=======");
			logger.info("======[U_couponController[u_coupon_add[参数description:" + description + ",coupon_amout:"
					+ coupon_amout + ",use_limit1:" + use_limit1 + ",coupon_count:" + coupon_count + ",end_time:"
					+ end_time + "]]]=======");

			// 地区信息 格式：江苏省/常州市/溧阳市
			String province = "";
			String city = "";
			String area = "";
			if (regioninfo != null && !"".equals(regioninfo.trim())) {
				String[] regions = regioninfo.split("/");
				int length = regions.length;
				if (length == 1) {
					province = regions[0];
				} else if (length == 2) {
					province = regions[0];
					city = regions[1];
				} else if (length >= 3) {
					province = regions[0];
					city = regions[1];
					area = regions[2];
				}

			}
			SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String create_time = sd.format(new Date());

			// 判断优惠金额有多少条
			int coupon_length = 0;
			if (coupon_amout != null) {
				coupon_length = coupon_amout.length;
			}

			ApiU_coupon u_coupon = new ApiU_coupon();
			u_coupon.setCorp_adress(corp_adress);
			u_coupon.setCoupon_cate_id(coupon_cate_id);
			u_coupon.setCorp_name(corp_name);
			u_coupon.setCorp_adress(corp_adress);
			u_coupon.setRange(Long.parseLong(range));
			u_coupon.setCorp_mobile(corp_mobile);
			u_coupon.setBusiness_hours(business_hours);
			u_coupon.setCoupon_type(Integer.parseInt(coupon_type));
			u_coupon.setDescription(description);
			u_coupon.setCity(city);
			u_coupon.setProvince(province);
			u_coupon.setArea(area);
			u_coupon.setCreate_time(create_time);
			u_coupon.setIs_active(1);
			u_coupon.setCorp_longitude(longitude);
			u_coupon.setCorp_latitude(latitude);
			if (coupon_length >= 1) {
				for (int i = 0; i < coupon_length; i++) {
					param = new HashMap<String, Object>();
					param.put("coupon_amout", Integer.parseInt(coupon_amout[i]));
					param.put("use_limit1", use_limit1[i]);
					param.put("coupon_count", Long.parseLong(coupon_count[i]));
					param.put("end_time", end_time[i]);
					list.add(param);
				}
			}

			if (coupon_id == null || (coupon_id.trim()).equals("")) {
				apiU_couponService.insertU_coupon_info(u_coupon, list);
			}
			// edit
			else {
				String[] coupon_id_list = request.getParameterValues("coupon_id_list");
				apiU_couponService.updateU_coupon_info(u_coupon, list, coupon_id_list);
			}
			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "添加成功！");
		} catch (Exception e) {
			map.put(Utils.RESULT, Utils.RESULT_RC_EXCEPTION);
			map.put(Utils.MESSAGE, "添加失败！");
			logger.error("======[U_couponController[u_coupon_add[编辑优惠券失败]]]=========", e);
		}
		//
		JsonUtil.printJson(response, JsonUtil.object2json(map));
	}

	/**
	 * 进入新增或者编辑页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "coupon-add-pre")
	public ModelAndView u_coupon_add_pre(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView("forward:/backstage/u_coupon_add.jsp");
		try {
			List<ApiT_enums> classify = apiT_enumsService.findT_enumssByItem_key("coupon_classify");
			List<ApiT_enums> classifys = apiT_enumsService.findT_enumssByParent_id(classify.get(0).getId() + "");
			mv.addObject("match_classifys_list", classifys);

			List<ApiT_enums> preferentia = apiT_enumsService.findT_enumssByItem_key("coupon_preferential");
			List<ApiT_enums> preferentias = apiT_enumsService.findT_enumssByParent_id(preferentia.get(0).getId() + "");
			mv.addObject("match_preferentias_list", preferentias);

			if (request.getParameter("id") != null) {
				String id = request.getParameter("id");
				ApiU_coupon u_coupon = apiU_couponService.findU_couponById(Integer.valueOf(id));
				mv.addObject("u_coupon", u_coupon);
				List<ApiU_coupon> apiU_coupon = new ArrayList<ApiU_coupon>();
				apiU_coupon.add(u_coupon);
				mv.addObject("apiU_coupon", apiU_coupon);
			}
		} catch (Exception e) {
			logger.error("======[U_couponController[u_coupon_add_pre[进入优惠券编辑页面失败]=======", e);
		}
		return mv;
	}
}
